import { Injectable } from '@nestjs/common';
import { InjectRepository } from '@nestjs/typeorm';
import { VipUsage } from './vipUsage.entity';
import { Repository } from 'typeorm';
import { serviceInfoLog,serviceErrorLog } from "src/common/out/logger/access.logger";

@Injectable()
export class VipUsageService {
    constructor(
        @InjectRepository(VipUsage)
        private vipUsageRepository: Repository<VipUsage>,
    ) { }

    async addCount(userid, countType) {
        try {
            const vipUsage = await this.vipUsageRepository.findOne({ where: { userid: userid } });

            if (vipUsage) {
                vipUsage[countType] += 1;
                await this.vipUsageRepository.save(vipUsage);
                serviceInfoLog(`User ${userid} updated ${countType} to ${vipUsage[countType]}`);
            } else {
                const newUsage = this.vipUsageRepository.create({
                    userid: userid,
                    [countType]: 1
                });
                await this.vipUsageRepository.save(newUsage);
                serviceInfoLog(`User ${userid} created new record with ${countType} set to 1`);
            }
        } catch (error) {
            serviceErrorLog(`Error add vip usage ${countType} count: ` + error);
        }
    }

    async addDiaryChatCnt(userid) {
        return this.addCount(userid, 'diaryChatCnt');
    }

    async addVisualChatCnt(userid) {
        return this.addCount(userid, 'visualChatCnt');
    }

    async addDiaryCnt(userid) {
        return this.addCount(userid, 'diaryCnt');
    }

    async addDiaryBillCnt(userid) {
        return this.addCount(userid, 'diaryBillCnt');
    }

    async getCount(userid, countType) {
        const vipUsage = await this.vipUsageRepository.findOne({ where: { userid: userid } });
        if (vipUsage) {
            return vipUsage[countType];
        } else {
            return 0
        }
    }

    async getDiaryChatCnt(userid) {
        return await this.getCount(userid, 'diaryChatCnt');
    }

    async getVisualChatCnt(userid) {
        return await this.getCount(userid, 'visualChatCnt');
    }

    async getDiaryCnt(userid) {
        return await this.getCount(userid, 'diaryCnt');
    }

    async getDiaryBillCnt(userid) {
        return await this.getCount(userid, 'diaryBillCnt');
    }

}


